import com.demo.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

public class ESTestDocInsert {

    public static void main(String[] args) throws Exception {
        //创建es客户端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200)));
        System.out.println(esClient);

        IndexRequest request = new IndexRequest();
        //方式1 这种方式会根据id 将数据进行新增 ，如果存在相同id，则会整体覆盖
        //request.index("user").id("1004");
        //不指定id的情况，es会自己生成一个随机串变成id
        request.index("user");

        //构建对象
        User user = new User();
        user.setName("zhangsan22");
        user.setSex("男性");
        user.setTel("1111");

        //向es插入数据，必须将数据转成json格式
        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user);
        request.source(userJson, XContentType.JSON);

        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);

        System.out.println(response.getResult());

        //关闭客户端连接
        esClient.close();
    }
}
